﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Security
{
	unsafe public class EncryptClass
	{
		unsafe public static string GetCode()
		{
			string strCUP = SystemInfo.GetMoc()[0];
			return Encrypt(strCUP);
		}

		unsafe private static string Encrypt(string str)
		{
			string temp = EncryptByMd5(str);
			return MyCrypto(temp);
		}

		unsafe private static string EncryptByMd5(string str)
		{
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] bt = Encoding.Default.GetBytes(str);//将待加密字符转为 字节型数组
			byte[] resualt = md5.ComputeHash(bt);//将字节数组转为加密的字节数组
			string pwds = BitConverter.ToString(resualt).Replace("-", "");//将数字转为string 型去掉内部的无关字符
			return pwds;
		}

		unsafe private static string MyCrypto(string str)
		{
			string pwd = "_zyf364@";

			DESCryptoServiceProvider des = new DESCryptoServiceProvider();
			//把字符串放到byte数组中


			//原来使用的UTF8编码，我改成Unicode编码了，不行
			byte[] inputByteArray = Encoding.Default.GetBytes(str);

			//建立加密对象的密钥和偏移量


			//使得输入密码必须输入英文文本
			des.Key = Encoding.ASCII.GetBytes(pwd);
			des.IV = Encoding.ASCII.GetBytes(pwd);
			MemoryStream ms = new MemoryStream();
			CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

			cs.Write(inputByteArray, 0, inputByteArray.Length);
			cs.FlushFinalBlock();
			StringBuilder ret = new StringBuilder();
			foreach (byte b in ms.ToArray())
			{
				ret.AppendFormat("{0:X2}", b);
			}
			ret.ToString();
			return ret.ToString();
		}
	}
}
